package com.ews.onlineexchange.navigation;

import java.util.Map;
import java.util.Set;

import javax.enterprise.context.spi.CreationalContext;
import javax.enterprise.inject.spi.Bean;
import javax.enterprise.inject.spi.BeanManager;
import javax.enterprise.inject.spi.CDI;
import javax.faces.application.ConfigurableNavigationHandler;
import javax.faces.application.NavigationCase;
import javax.faces.context.FacesContext;

import com.ews.onlineexchange.service.EntityHome;

public class NavigationHandler extends ConfigurableNavigationHandler {
	
	private NavigationHandler parent;

    public NavigationHandler(NavigationHandler parent) {
        this.parent = parent;
    }

	@Override
	public void handleNavigation(FacesContext context, String fromAction, String outcome) {
		if (fromAction.equals("someAction")) {
			BeanManager theBeanManager = getBeanManager(context);
			Bean bean = theBeanManager.getBeans("yourCDIBean").iterator().next();
			CreationalContext ctx = theBeanManager.createCreationalContext(bean);
			EntityHome o = (EntityHome) theBeanManager.getReference(bean, bean.getClass(), ctx); 
			o.getConversation().end(); // end the conversation from the bean reference
		}

		// proceed with normal navigation
		parent.handleNavigation(context, fromAction, outcome);

	}

	public BeanManager getBeanManager(FacesContext facesContext) {
		BeanManager cdiBeanManager = CDI.current().getBeanManager();
		return cdiBeanManager;
	}

    @Override
    public NavigationCase getNavigationCase(FacesContext context, String fromAction, String outcome) {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCase(context, fromAction, outcome);
        } else {
            return null;
        }
    }

    @Override
    public Map<String, Set<NavigationCase>> getNavigationCases() {
        if (parent instanceof ConfigurableNavigationHandler) {
            return ((ConfigurableNavigationHandler) parent).getNavigationCases();
        } else {
            return null;
        }
    }

}